const Koa = require('koa');
const websockify = require('koa-websocket');
const app = websockify(new Koa());
const path = require('path');
// 适配 vue history 中间件
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const parameter = require('koa-parameter');
process.env.NODE_ENV === 'development' ? require('./__TEST__') : require('./__execute__');

// 错误处理程序 -- 在html中打印出错误
require('koa-onerror')(app);

// 记录器
app.use(async (ctx, next) => {
  const start = +new Date();
  await next(); // 执行下一个中间件
  const ms = +new Date() - start; // 计算时间差，例如 80
  ctx.set('X-Response-Time', `${ms}ms`); // 记录/设置 时间差
});

// 中间件
// handle fallback for HTML5 history API
app.use(historyApiFallback({ whiteList: ['/api'] }));
app.use(
  require('koa2-cors')({
    origin(ctx) {
      // if (/^\/script\//.test(ctx.path)) {
      //   return '*';
      // }
      return '*';
    }
  })
);
app.use(require('koa-logger')());
app.use(require('koa-bodyparser')({ enableTypes: ['json', 'form', 'text'] }));
app.use(require('koa-json')());
parameter(app);
app.use(require('koa-static')(path.resolve(__dirname, './public')));

// // 路由
// const API_ROUTES = require('./routes');
// app.use(API_ROUTES.routes());
// app.use(API_ROUTES.allowedMethods());

// 错误处理
app.on('error', async (error) => {
  console.error(`[err] ${error.message}`);
});

const port = 8001;
app.listen(port, () => {
  console.info(`>>> Server listen on ${port} | ${process.env.NODE_ENV}`);
});

module.exports = app;
